from utils.getPublicData import *
from models.house_info import house_info
from models.history import History
from models.user import User
import json
from datetime import datetime

def getHomeHisotryData():
    return History.query.all()

def getPriceCityData(houseList):
    xData = ["<=4000",'4000-6000','6000-8000','8000-10000','10000-12000','12000-15000','15000-18000','>=20000']
    y1Data = [0 for x in range(len(xData))]
    for h in houseList:
        if int(h.price) <= 4000:
            y1Data[0] += 1
        elif int(h.price) <= 6000:
            y1Data[1] += 1
        elif int(h.price) <= 8000:
            y1Data[2] += 1
        elif int(h.price) <= 10000:
            y1Data[3] += 1
        elif int(h.price) <= 12000:
            y1Data[4] += 1
        elif int(h.price) <= 15000:
            y1Data[5] += 1
        elif int(h.price) <= 18000:
            y1Data[6] += 1
        elif int(h.price) > 20000:
            y1Data[7] += 1
    return xData,y1Data

def getOpen_dateCityData(houseList):
    xData = calculate_average_price(houseList, 'open_date')
    sorted_data = list(sorted(xData.items(), key=lambda x: x[0],reverse=True))
    return [x[0] for x in sorted_data],[x[1] for x in sorted_data]

def getTableDatahouse():
    return getAllhouseInfoDataMap()

def getHomeRadarData():
    houseList = getAllhouseInfoData()
    cityDic = {}
    for h in houseList:
        for j in cityList:
            for k in j['city']:
                if k.find(h.city) != -1:
                    if cityDic.get(j['province'],-1) == -1:
                        cityDic[j['province']] = 1
                    else:
                        cityDic[j['province']] += 1
    data1 = [{'name':x[0],'value':x[1]} for x in cityDic.items()]
    data2 = [{'name':x[0],'max':450} for x in cityDic.items()]
    return data1,data2

def calculate_average_price(house_data,field):
    city_prices = {}
    city_counts = {}
    for house in house_data:
        if field == 'city':
            city = house.city
        elif field == 'open_date':
            city = house.open_date

        price = int(house.price)

        # 累计每个城市的总售价和房屋数量
        if city in city_prices:
            city_prices[city] += price
            city_counts[city] += 1
        else:
            city_prices[city] = price
            city_counts[city] = 1

    average_prices = {}
    for city in city_prices:
        average_prices[city] = round(city_prices[city] / city_counts[city],1)

    return average_prices

def getCityPriceChinaData():
    houseList = getAllhouseInfoData()
    average_prices = calculate_average_price(houseList,'city')
    cityDic = {}
    for key,value in average_prices.items():
        for j in cityList:
            for k in j['city']:
                if k.find(key) != -1:
                    cityDic[j['province']] = value

    cityListData = []
    for key,value in cityDic.items():
        cityListData.append({
            'name':key,
            'value':value
        })


    return cityListData

def getTotalPriceData(houseList):
    data = []
    for index,i in enumerate(houseList):
        if len(i.totalPrice_range) != 1:
            data.append({
                'value':[float(i.totalPrice_range[0]),float(i.totalPrice_range[1])],
                'symbolSize':index * 1
            })

    return data

def getHisotryBarCharData(username):
    user = User.query.filter_by(user_name=username).first()
    userHisotry = History.query.filter_by(user=user).all()
    cityBarData = {}
    for i in userHisotry:
        if cityBarData.get(i.city,-1) == -1:
            cityBarData[i.city] = i.price
        else:
            cityBarData[i.city] += i.price
    data = []
    for key,value in cityBarData.items():
        data.append({
            'name':key,
            'value':value
        })
    return data

def getHomeTagData(username):
    houseList = getAllhouseInfoData()
    maxPrice = 0
    maxhouseTypeDic = {}
    maxSaleStatusDic = {}
    for i in houseList:
        if maxPrice < int(i.price):
            maxPrice = int(i.price)
        if maxhouseTypeDic.get(i.houseType,-1) == -1:
            maxhouseTypeDic[i.houseType] = 1
        else:
            maxhouseTypeDic[i.houseType] += 1

        if maxSaleStatusDic.get(i.sale_status,-1) == -1:
            maxSaleStatusDic[i.sale_status] = 1
        else:
            maxSaleStatusDic[i.sale_status] += 1

    maxhouseTypeDicSort = sorted(maxhouseTypeDic.items(),key=lambda x:x[1],reverse=True)
    maxSaleStatusDicSort = sorted(maxSaleStatusDic.items(),key=lambda x:x[1],reverse=True)
    if maxSaleStatusDicSort[0][0] == '1':
        sale_statusMax = '在售'
    elif   maxSaleStatusDicSort[0][0] == '2':
        sale_statusMax = '已售'
    elif   maxSaleStatusDicSort[0][0] == '3':
        sale_statusMax = '出租中'
    elif   maxSaleStatusDicSort[0][0] == '4':
        sale_statusMax = '已出租'
    elif   maxSaleStatusDicSort[0][0] == '5':
        sale_statusMax = '预售'
    elif   maxSaleStatusDicSort[0][0] == '6':
        sale_statusMax = '其他'
    user = User.query.filter_by(user_name=username).first()
    userHisotry = History.query.filter_by(user=user).all()
    maxPrice = 0
    countCity = {}
    for i in userHisotry:
        if maxPrice < float(i.price):
            maxPrice = float(i.price)
        if countCity.get(i.city,-1) == -1:
            countCity[i.city] = 1
        else:
            countCity[i.city] += 1
    sortCountCity = list(sorted(countCity.items(),key=lambda x:x[1],reverse=True))
    return len(houseList),maxPrice,maxhouseTypeDicSort[0][0],sale_statusMax,len(userHisotry),maxPrice,sortCountCity[0][0]

def getDetailCharRomms_descData(houseList):
    rooms_desc = [x.rooms_desc for x in houseList]
    xData = list(set([room for rooms in rooms_desc for room in rooms if room != False]))
    yData = [0 for x in range(len(xData))]
    for i in houseList:
        for j in i.rooms_desc:
            for index,k, in enumerate(xData):
                if k == j:
                    yData[index] += 1
    dataDic = []
    for index,i in enumerate(xData):
        if i != '':
            dataDic.append({
                'name':i,
                'value':yData[index]
            })
    return dataDic

def getDetailCharArea_rangeData(houseList,defaultType):
    if defaultType == 'small':
        ranges = [
            '0-40',
            '40-60',
            '60-80',
            '80-100',
            '100-120',
            '120-150',
            '150-n'
        ]
        yData = [0 for x in range(len(ranges))]
        for i in houseList:
            if i.area_range[0] != '':
                if float(i.area_range[0]) <= int(40):
                    yData[0] += 1
                elif float(i.area_range[0]) <= int(60):
                    yData[1] += 1
                elif float(i.area_range[0]) <= int(80):
                    yData[2] += 1
                elif float(i.area_range[0]) <= int(100):
                    yData[3] += 1
                elif float(i.area_range[0]) <= int(120):
                    yData[4] += 1
                elif float(i.area_range[0]) <= int(150):
                    yData[5] += 1
                elif float(i.area_range[0]) > int(150):
                    yData[6] += 1
        return ranges,yData
    else:
        ranges = [
            '80-100',
            '100-110',
            '110-120',
            '120-130',
            '130-140',
            '140-150',
            '150-160',
            '160-170',
            '170-180',
            '200-n'
        ]
        yData = [0 for x in range(len(ranges))]
        for i in houseList:
            if i.area_range[0] != '':
                if float(i.area_range[0]) <= int(100):
                    yData[0] += 1
                elif float(i.area_range[0]) <= int(110):
                    yData[1] += 1
                elif float(i.area_range[0]) <= int(120):
                    yData[2] += 1
                elif float(i.area_range[0]) <= int(130):
                    yData[3] += 1
                elif float(i.area_range[0]) <= int(140):
                    yData[4] += 1
                elif float(i.area_range[0]) <= int(150):
                    yData[5] += 1
                elif float(i.area_range[0]) <= int(160):
                    yData[6] += 1
                elif float(i.area_range[0]) <= int(170):
                    yData[6] += 1
                elif float(i.area_range[0]) <= int(180):
                    yData[6] += 1
                elif float(i.area_range[0]) > int(200):
                    yData[6] += 1
        return ranges, yData

def getTypeCharhouseDecorationData(houseList):
    houseDecorationDic = {}
    for i in houseList:
        if houseDecorationDic.get(i.houseDecoration,-1) == -1:
            houseDecorationDic[i.houseDecoration] = 1
        else:
            houseDecorationDic[i.houseDecoration] += 1
    houseDecorationData = []
    for key,value in houseDecorationDic.items():
        if key != '':
            houseDecorationData.append({
                'name':key,
                'value':value
            })
    return houseDecorationData

def getTypeCharhouseTypeData(houseList):
    houseDecorationDic = {}
    for i in houseList:
        if houseDecorationDic.get(i.houseType,-1) == -1:
            houseDecorationDic[i.houseType] = 1
        else:
            houseDecorationDic[i.houseType] += 1
    houseDecorationData = []
    for key,value in houseDecorationDic.items():
        if key != '':
            houseDecorationData.append({
                'name':key,
                'value':value
            })
    return houseDecorationData

def getAnthorCharSale_statusData(houseList):
    saleStatusDic = {}
    for i in houseList:
        if int(i.sale_status) == 1:
            if saleStatusDic.get('在售',-1) == -1:
                saleStatusDic['在售'] = 1
            else:
                saleStatusDic['在售'] += 1
        elif int(i.sale_status) == 2:
            if saleStatusDic.get('已售',-1) == -1:
                saleStatusDic['已售'] = 1
            else:
                saleStatusDic['已售'] += 1
        elif int(i.sale_status) == 3:
            if saleStatusDic.get('出租中',-1) == -1:
                saleStatusDic['出租中'] = 1
            else:
                saleStatusDic['出租中'] += 1
        elif int(i.sale_status) == 4:
            if saleStatusDic.get('已出租',-1) == -1:
                saleStatusDic['已出租'] = 1
            else:
                saleStatusDic['已出租'] += 1
        elif int(i.sale_status) == 5:
            if saleStatusDic.get('预售',-1) == -1:
                saleStatusDic['预售'] = 1
            else:
                saleStatusDic['预售'] += 1
        elif int(i.sale_status) == 6:
            if saleStatusDic.get('其他',-1) == -1:
                saleStatusDic['其他'] = 1
            else:
                saleStatusDic['其他'] += 1
    saleStatusData = []
    for key,value in saleStatusDic.items():
        saleStatusData.append({
            'name':key,
            'value':value
        })
    return saleStatusData

def getAnthorCharOn_timeData(houseList):
    cityDic = {}
    for i in houseList:
        if i.on_time == '0000-00-00 00:00:00':
            if cityDic.get(i.city,-1) == -1:
                cityDic[i.city] = 1
            else:
                cityDic[i.city] += 1
    return list(cityDic.keys()),list(cityDic.values())




def getTagData(houseList):
    tagDic = {}
    for i in houseList:
        for j in i.tags:
            if tagDic.get(j,-1) == -1:
                tagDic[j] = 1
            else:
                tagDic[j] += 1
    return list(tagDic.keys()),list(tagDic.values())

